package org.bw.bookstore.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.bw.bookstore.book.mapper.MemberMapper;
import org.bw.bookstore.book.service.MemberService;
import org.bw.bookstore.book.utils.OssUtil;
import org.bw.bookstore.book.utils.QRCodeUtil;
import org.bw.bookstore.common.entity.TbStaffMember;
import org.bw.bookstore.common.entity.TbUserInfo;
import org.bw.bookstore.common.utils.ConstantSet;
import org.bw.bookstore.common.utils.ResponseResult;
import org.bw.bookstore.common.utils.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 范欣宜
 * @Date: 2020/10/22 15:22
 **/

@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, TbUserInfo> implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberService memberService;

    @Override
    public ResponseResult faceVerify(String humanFace) {
        return null;
    }

    /**
     * @Description:二维码验证
     * @Author: 范欣宜
     * @Date: 2020/10/24 14:43
     * @param mobile: 手机号
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult scanCodeVerify(String mobile) {
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper<TbUserInfo> queryWrapper = new QueryWrapper<TbUserInfo>();

        //手机号是否相同
        queryWrapper.lambda().eq(TbUserInfo::getMobile,mobile);
        TbUserInfo userInfo = memberMapper.selectOne(queryWrapper);
        //没有此用户
        if (userInfo==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("没有此用户");
            return result;
        }
        //取出存入redis里面的二维码
        String redisqrCode = (String) redisTemplate.opsForValue().get(mobile);
        //验证码失效
        if (redisqrCode==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("二维码失效");
            return result;
        }else {
            log.info(redisqrCode);

            //验证通过
            if (redisqrCode.equals(mobile)){
                result.setMessage("验证通过");

            }else{
                //验证码不正确
                result.setSuccess(false);
                result.setCode(-1);
                result.setMessage("二维码不正确");

            }
        }
        return result;

    }


    /**
     * @Description:手机号注册
     * @Author: 范欣宜
     * @Date: 2020/10/24 14:43
     * @param mobile: 手机号
     * @param verification: 验证码
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult phoneRegister(String mobile, String verification) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<Object, Object> resultMap = new HashMap<>();
        QueryWrapper<TbUserInfo> queryWrapper = new QueryWrapper<TbUserInfo>();
        //手机号是否相同
        queryWrapper.lambda().eq(TbUserInfo::getMobile,mobile);
        TbUserInfo userInfo = memberMapper.selectOne(queryWrapper);
        //手机号已存在
        if (userInfo!=null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("该手机号已注册");
            return result;
        }

        //取出存入redis里面的验证码
        String redisVerification = (String) redisTemplate.opsForValue().get(mobile);
        if (redisVerification==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("验证码失效");
            return result;
        } else {
            //判断验证码是否正确
            if (redisVerification.equals(verification)){

                TbUserInfo tbUserInfo = new TbUserInfo();
                //添加生成的随机用户标识
                tbUserInfo.setCode(StringTools.getRandomString(10));

                //添加会员码
                tbUserInfo.setMemberCode(StringTools.getRandomString(8));

                tbUserInfo.setDeleted(ConstantSet.NOT);
                //添加手机号
                tbUserInfo.setMobile(mobile);
                //添加创建时间
                tbUserInfo.setCreateTime(new Date());
                //添加
                memberMapper.insert(tbUserInfo);
            }else {
                result.setSuccess(false);
                result.setCode(-1);
                result.setMessage("验证码不正确");
            }
        }
        return result;
    }

    /**
     * @Description:手机号登录
     * @Author: 范欣宜
     * @Date: 2020/10/24 14:43
     * @param mobile: 手机号
     * @param verification: 验证码
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult phoneLogin(String mobile, String verification) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<Object, Object> resultMap = new HashMap<>();
        QueryWrapper<TbUserInfo> queryWrapper = new QueryWrapper<TbUserInfo>();
        //手机号是否相同
        queryWrapper.lambda().eq(TbUserInfo::getMobile,mobile);
        TbUserInfo userInfo = memberMapper.selectOne(queryWrapper);
        //没有此用户
        if (userInfo==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("请先注册");
            return result;
        }
        //取出存入redis里面的验证码
        String redisVerification = (String) redisTemplate.opsForValue().get(mobile);
        if (redisVerification==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("验证码失效");
        } else {
            //判断验证码是否正确
            if (redisVerification.equals(verification)){
                result.setSuccess(true);
                result.setMessage("登录成功");

            }else {
                //验证码不正确
                result.setSuccess(false);
                result.setCode(-1);
                result.setMessage("验证码不正确");
            }
        }
        resultMap.put("userInfo", userInfo);
        result.setResult(resultMap);
        return result;
    }

    /**
     * @Description:获取验证码
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @param mobile: 手机号
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult getVerification(String mobile) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(15);
        //生成随机的四位验证码
        String verification = String.valueOf((int)((Math.random()*9+1)*1000));
        log.info("验证码"+verification);
        //设置过期时间30秒
        redisTemplate.opsForValue().set(mobile,verification);
        redisTemplate.expire(mobile,30, TimeUnit.SECONDS);
        //发送验证码
        // DuanxinUtils.sendDuanxin(mobile,verification);
        resultMap.put("verification",verification);
        result.setResult(resultMap);
        return result;
    }

    /**
     * @Description:生成二维码
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @param mobile: 手机号
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult generateCode(String mobile) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(15);
        // 存放在二维码中的内容
        String text = mobile;
        // 嵌入二维码的图片路径
         String imgPath = "D:\\workSpace\\fileDB\\cat.jpg";
        // 生成的二维码的路径及名称
        String destPath = "D:\\workSpace\\fileDB\\code.jpg";
        //生成二维码
        try {
           QRCodeUtil.encode(text, imgPath, destPath, true);
         //   QRCodeUtil.encode(text, destPath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        // 解析二维码
//        String str = null;
//        try {
//            str = QRCodeUtil.decode(destPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        // 打印出解析出的内容
//        System.out.println(str);

        //设置过期时间30秒
        redisTemplate.opsForValue().set(mobile,text);
        redisTemplate.expire(mobile,30, TimeUnit.SECONDS);
        resultMap.put("text",text);
        result.setResult(resultMap);
        return result;

    }


    /**
     * @Description:解析二维码
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult analysisCode(String qrCodeUrl) {
        ResponseResult result = ResponseResult.SUCCESS();

        // 嵌入二维码的图片路径
        // String imgPath = "D:\\workSpace\\fileDB\\cat.jpg";
        // 生成的二维码的路径及名称
        String destPath = "D:\\workSpace\\fileDB\\code.jpg";

        // 解析二维码
        String str = null;
        try {
            str = QRCodeUtil.decode(destPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 打印出解析出的内容
        System.out.println(str);
        result.setResult(destPath);
        return result;

    }

    /**
     * @Description:会员注册
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @param userInfo: 会员信息
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult staffMemberRegister(TbUserInfo userInfo) {
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper<TbUserInfo> queryWrapper = new QueryWrapper<TbUserInfo>();

        queryWrapper.lambda().eq(TbUserInfo::getIdCard,userInfo.getIdCard());
        TbUserInfo tbUserInfo = memberMapper.selectOne(queryWrapper);
        //该用户已存在
        if (tbUserInfo!=null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("该用户已存在");
            return result;
        }

        tbUserInfo = new TbUserInfo();
        //添加生成的随机用户标识
        tbUserInfo.setCode(StringTools.getRandomString(10));
        //添加手机号
        tbUserInfo.setMobile(userInfo.getMobile());
        //添加创建时间
        tbUserInfo.setCreateTime(new Date());
        //添加身份证
        tbUserInfo.setIdCard(userInfo.getIdCard());
        //添加年龄
        tbUserInfo.setAge(userInfo.getAge());
        //添加邮箱
        tbUserInfo.setEmail(userInfo.getEmail());
        //添加会员码(随机生成8位)
        tbUserInfo.setMemberCode(StringTools.getRandomString(8));
        //添加会员真实姓名
        tbUserInfo.setRealName(userInfo.getRealName());
        //添加会员姓名
        tbUserInfo.setUserName(userInfo.getUserName());
        //添加性别
        tbUserInfo.setSex(userInfo.getSex());
        //面部url
        tbUserInfo.setHumanFaceUrl(userInfo.getHumanFaceUrl());
        //生成盐
        String salt = StringTools.getRandomString(32);
        tbUserInfo.setUserSale(salt);
        //密码+.+盐
        String password=tbUserInfo.getUserPass()+"."+salt;
        //MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("pass:"+md5Password);
        tbUserInfo.setUserPass(md5Password);
        //添加会员状态
        tbUserInfo.setDeleted(ConstantSet.NOT);
        //添加
        memberMapper.insert(tbUserInfo);


        return result;
    }

    /**
     * @Description:会员信息修改
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @param userInfo: 会员信息
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult updateStaffMember(TbUserInfo userInfo) {
        ResponseResult result = ResponseResult.SUCCESS();
        TbUserInfo tbUserInfo = memberMapper.selectById(userInfo.getId());

        //该用户不存在
        if (tbUserInfo==null){
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("该用户不存在");
            return result;
        }

        //修改手机号
        tbUserInfo.setMobile(userInfo.getMobile());
        //修改修改时间
        tbUserInfo.setUpdateTime(new Date());
        //修改身份证
        tbUserInfo.setIdCard(userInfo.getIdCard());
        //修改年龄
        tbUserInfo.setAge(userInfo.getAge());
        //修改邮箱
        tbUserInfo.setEmail(userInfo.getEmail());
        //修改会员真实姓名
        tbUserInfo.setRealName(userInfo.getRealName());
        //修改会员姓名
        tbUserInfo.setUserName(userInfo.getUserName());
        //修改性别
        tbUserInfo.setSex(userInfo.getSex());
        //修改图片url
        tbUserInfo.setHumanFaceUrl(userInfo.getHumanFaceUrl());
        //修改
        memberMapper.updateById(tbUserInfo);


        return result;
    }

    /**
     * @Description:获取会员信息
     * @Author: 范欣宜
     * @Date: 2020/10/24 16:33
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult getMember() {

        ResponseResult result = ResponseResult.SUCCESS();
        //查询会员
        List<TbUserInfo> tbUserInfos = memberMapper.selectList(new QueryWrapper<>());
        result.setResult(tbUserInfos);
        return result;
    }

    /**
     * TODO 范欣宜 分页查询全部会员
     * @Author: 范欣宜
     * @Date: 2020/10/28 18:45
     * @param currentPage: 当前页
     * @param pageSize: 每页多少条
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult getMemberByPage(Integer currentPage, Integer pageSize) {
        ResponseResult result = ResponseResult.SUCCESS();
        //分页
        Page<TbUserInfo> page = new Page<>(currentPage,pageSize);
        IPage<TbUserInfo> tbUserInfoIPage = memberMapper.selectPage(page, new QueryWrapper<>());
        result.setResult(tbUserInfoIPage);
        return result;
    }


//    /**
//     * TODO 范欣宜 上传
//     * @Author: 范欣宜
//     * @Date: 2020/10/21 19:27
//     * @return: com.bw.common.utils.ResponseResult
//     **/
//    @Override
//    public ResponseResult upload(MultipartFile file) {
//        //mvc提供的参数file
//        ResponseResult result = ResponseResult.SUCCESS();
//        try{
//            //1.获取文件后缀   getOriginalFilename文件的全名
//            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
//            //2.获取路径
//            String dirPath="D:\\workSpace\\fileDB\\";
//            String path= UUID.randomUUID()+ext;
//            //3.将文件复制到对应服务器的路径下
//            File mFile = new File(dirPath+path);
//            file.transferTo(mFile);
//            //4.将文件的存储路径返回给前段
//            Map map = new HashMap();
//            //将路径存入map集合
//            map.put("path",path);
//            //存入result中
//            result.setResult(map);
//        }catch (Exception e){
//            result.setSuccess(false);
//            result.setMessage("上传失败"+e.toString());
//        }
//        return result;
//    }

    /**
     * TODO 范欣宜 下载
     * @Author: 范欣宜
     * @Date: 2020/10/21 19:27
     **/
    @Override
    public void download(String path, HttpServletResponse response) {
        //判断路径是否为空
        if(path==null){
            return;
        }
        try{
            //读取图片文件流
            InputStream inputStream = new FileInputStream("D:\\workSpace\\fileDB\\"+path);
            //定义每次读取输入流当中的多少字节
            byte[] b = new byte[1024];
            //记录每次读取字节流的位置
            int len;
            while((len = inputStream.read(b))>0){
                response.getOutputStream().write(b,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public ResponseResult delMember(Integer id) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();

        //--1 判断工作人员是否存在
        TbUserInfo tbUserInfo= memberMapper.selectById(id);
        //会员不存在
        if(tbUserInfo == null) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("会员不存在");
            return result;
        }

        //会员已删除
        if(!tbUserInfo.getDeleted().equals(ConstantSet.NOT)) {
            result.setSuccess(false);
            result.setCode(-1);
            result.setMessage("会员已删除");
            return result;
        }

        //--2 设置删除标志
        tbUserInfo.setDeleted(ConstantSet.YES);
        //逻辑删除
        memberMapper.updateById(tbUserInfo);

        resultMap.put("tbUserInfo",tbUserInfo);
        result.setResult(resultMap);

        return result;
    }

    @Override
    public ResponseResult uploadImg(MultipartFile file) {
        ResponseResult result = ResponseResult.SUCCESS();
        Map<String, Object> resultMap = new HashMap<>();

        //上传图片并返回
        String url = OssUtil.uploadAliyun(file, file.getOriginalFilename());
        System.err.println(url);
        resultMap.put("url", url);
        result.setResult(resultMap);
        return result;

//        ResponseResult result=ResponseResult.SUCCESS();
//        Map<String, Object> resultMap = new HashMap<>();
//        if(file.isEmpty()){
//            log.info("文件为空");
//            result.setSuccess(false);
//            result.setCode(-1);
//            result.setMessage("文件不能为空");
//            return result;
//
//        }
//        //获取图片原始名称
//        String fileName = file.getOriginalFilename();
//        int size = (int) file.getSize();
//        log.info(fileName + "-->" + size);
//
//        UUID uuid = UUID.randomUUID();
//        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
//        String newName = uuid.toString() + suffix;
//
//        String url = OssUtil.uploadAliyun(file, newName);
//
//
//        log.info("上传成功: " + url);
//
//        resultMap.put("url", url);
//        result.setResult(resultMap);
//        return result;
    }

    @Override
    public ResponseResult getMemberById(Integer id) {
        ResponseResult result = ResponseResult.SUCCESS();
        //创建map集合，用于存储对象
        HashMap<String, Object> resultMap = new HashMap<>();
        //条件查询 返回实体对象
        TbUserInfo tbUserInfo = memberMapper.selectOne(new QueryWrapper<TbUserInfo>()
                .eq("id", id)
                .last("limit 1"));
        //判断是否存在
        if (tbUserInfo==null){
            result.setSuccess(false);
            result.setMessage("会员不存在");
            return result;
        }

        //存入map集合
        resultMap.put("tbUserInfo",tbUserInfo);
        result.setResult(resultMap);
        return  result;
    }


}
